package com.example.demo.Controller;

import com.example.demo.core.JsonUtil;
import com.example.demo.core.MD5Util;
import com.example.demo.core.NotFoundException;
import com.example.demo.core.Response;
import com.example.demo.core.security.JWTUtil;
import com.example.demo.model.Admin;
import com.example.demo.model.User;
import com.example.demo.service.BookBorrowAndFeeService;
import com.example.demo.service.UserService;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    BookBorrowAndFeeService bookBorrowAndFeeServiceImpl;


    /**
     * 用户登入
     * @param body
     * @param request
     * @return
     */
    @PostMapping("/login")
    public Object userLogin(@RequestBody String body, HttpServletRequest request)
    {
        String name = JsonUtil.parseString(body, "name");
        String password = MD5Util.md5(JsonUtil.parseString(body, "password"));

        User user=userService.userLogin(name, password);
        if(user==null)
        {
            return Response.fail(508,"登录失败，用户名或密码错误");
        }
        Map<String,String> map=new HashMap<String,String>();
        map.put("token",JWTUtil.getToken(String.valueOf(user.getUserId()),name,user.getRole(),"user",password));
        return Response.ok(map);
    }

    /**
     * 查询自己的账号信息
     * @param request
     * @return
     */
    @GetMapping("/info/select")
    @RequiresAuthentication
    public Object selectSelfInfo(HttpServletRequest request)
    {
        String token=request.getHeader("Authorization");
        String id=JWTUtil.getId(token);
        List<User> users=userService.selectByCondition(id,null,null,null,null);
        if(users.size()==0)
        {
            return Response.ok("User Not Found");
        }
        return Response.ok(users.get(0));
    }

    /**
     * 修改自己的账号信息
     * @param body
     * @param request
     * @return
     */
    @PostMapping("/info/update/self")
    @RequiresAuthentication
    public Object updateSelfInfo(@RequestBody String body, HttpServletRequest request)
    {
        String name = JsonUtil.parseString(body, "name");
        String phone = JsonUtil.parseString(body, "phone");
        String email = JsonUtil.parseString(body, "email");


        String token=request.getHeader("Authorization");
        String currentName=JWTUtil.getName(token);
        String id=JWTUtil.getId(token);
        if(!currentName.equals(name)&&userService.selectByCondition(null,name,null,null,"0").size()!=0)//说明重名
        {
            return Response.fail(401,"用户名重复");
        }
        return Response.ok(userService.userUpdate(new User(Integer.parseInt(id),name,null,phone,email,null,null)));
    }

    /**
     * 修改自己的密码
     */
    @PostMapping("/info/update/selfpassword")
    @RequiresAuthentication
    public Object updateSelfPassword(@RequestBody String body, HttpServletRequest request)
    {
        String oldPassword = MD5Util.md5(JsonUtil.parseString(body, "oldPassword"));
        String newPassword = MD5Util.md5(JsonUtil.parseString(body, "newPassword"));
        String token=request.getHeader("Authorization");
        String name=JWTUtil.getName(token);
        if(userService.userLogin(name, oldPassword)==null)
        {
            return Response.fail(401,"旧密码错误");
        }
        return Response.ok(userService.userUpdate(new User(Integer.parseInt(JWTUtil.getId(token)),null,newPassword,null,null,null,null)));
    }

    /**
     * 添加用户
     * @param body
     * @param request
     * @return
     */
    @PostMapping("/add")
    public Object addUser(@RequestBody String body, HttpServletRequest request)
    {
        String name = JsonUtil.parseString(body, "name");
        String password = MD5Util.md5(JsonUtil.parseString(body, "password"));
        String phone = JsonUtil.parseString(body, "phone");
        String email = JsonUtil.parseString(body, "email");

        //是否用户名重复
        if(userService.selectByCondition(null,name,null,null,"0").size()>=1)
        {
            return Response.fail(401,"该用户名已经存在");
        }
        return Response.ok(userService.userInsert(new User(null,name,password,phone,email,null,null)));
    }

    /**
     * 通过条件查询所有用户信息
     * @param id
     * @param name
     * @param phone
     * @param email
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/info/select/all")
    @RequiresPermissions(logical = Logical.AND, value = {"user:info:select:all"})
    public Object userSelectByCondition(String id, String name, String phone,String email,
                                        @RequestParam(defaultValue = "1") Integer page,
                                        @RequestParam(defaultValue = "10") Integer limit) throws NotFoundException {
        if ("".equals(id))
            id=null;
        if ("".equals(name))
            name=null;
        if ("".equals(phone))
            phone=null;
        if ("".equals(email))
            email=null;

        List<User> users=userService.selectByCondition(id,name,phone,email,null);

        if (users.size()==0)
            throw new NotFoundException("查询的用户为空");

        return Response.okList(users,page,limit);
    }

    /**
     * 修改所有用户数据
     * @param body
     * @param request
     * @return
     */
    @PostMapping("/info/update/all")
    @RequiresPermissions(logical = Logical.AND, value = {"user:info:update:all"})
    public Object updateUser(@RequestBody String body, HttpServletRequest request)
    {
        String name = JsonUtil.parseString(body, "name");
        String password = MD5Util.md5(JsonUtil.parseString(body, "password"));
        String phone = JsonUtil.parseString(body, "phone");
        String email = JsonUtil.parseString(body, "email");
        String role = JsonUtil.parseString(body, "role");
        String id = JsonUtil.parseString(body, "id");

        String originName=userService.selectByCondition(id,null,null,null,"0").get(0).getUserName();
        if (!originName.equals(name)&&userService.selectByCondition(null,name,null,null,"0").size()>=1)
        {
            return Response.fail(401,"该用户名已经存在");
        }
        //否则表示只是修改个人数据
        return Response.ok(userService.userUpdate(new User(Integer.parseInt(id),name,password,phone,email,null,role)));
    }

    /**
     * 懒惰删除用户数据
     * @param body
     * @param request
     * @return
     */
    @PostMapping("/info/delete/all")
    @RequiresPermissions(logical = Logical.AND, value = {"user:info:delete:all"})
    public Object deleteUser(@RequestBody String body, HttpServletRequest request)
    {
        String id = JsonUtil.parseString(body, "id");

        if ("".equals(id))
            id=null;

        if (id==null)
            return Response.fail(401,"用户id不允许为空");
        List<User> users=userService.selectByCondition(id,null,null,null,null);
        if(users.size()==0)
        {
            return Response.fail(401,"用户不存在");
        }

        if (bookBorrowAndFeeServiceImpl.isBorrow(null, Integer.valueOf(id)))
            return Response.fail(401,"用户还有借阅记录不允许删除");


        return Response.ok(userService.userDelete(new User(Integer.parseInt(id),null,null,null,null,null,null)));
    }
}
